<template>
  <div class="modal" v-if="dish" @click="handleBackgroundClick">
    <div class="modal-content" @click.stop>
<!--      <span class="close-button" @click="close">&times;</span>-->

      <div class="content-container">

        <!-- Left Panel for Editing the Dish -->
        <div class="left-panel">
          <h2>修改菜品信息</h2>

          <form @submit.prevent="submitDish">
            <input v-model="form.name" type="text" placeholder="菜品名称" />
            <textarea v-model="form.description" placeholder="菜品描述"></textarea>
            <a>修改菜品图片</a> <input type="file" @change="handleFileUpload" />

<!--            <select v-model="form.is_on_shelf">-->
<!--              <option value="on">上架</option>-->
<!--              <option value="off">下架</option>-->
<!--            </select>-->

            <button type="submit">更新</button>
          </form>
        </div>

        <!-- Right Panel for Displaying Ingredients Table -->
        <div class="right-panel">
          <div class="table-container">
            <h2>原料信息:</h2>

          <table class="ingredients-table" v-if="allIngredients.length">
            <thead>
            <tr>
              <th>原料名称</th>
              <th>采购日期</th>
              <th>供应商</th>
              <th>选择</th> <!-- New column for checkboxes -->
            </tr>
            </thead>
            <tbody>
            <tr v-for="ingredient in allIngredients" :key="ingredient.ingredient_id">
              <td>{{ ingredient.name }}</td>
              <td>{{ ingredient.purchase_date }}</td>
              <td>{{ ingredient.supplier }}</td>
              <td>
                <input type="checkbox" :checked="isIngredientSelected(ingredient.ingredient_id)" @change="handleCheckboxChange(ingredient.ingredient_id, $event)">
              </td>
            </tr>
            </tbody>
          </table>
        </div>
        </div>
      </div>
    </div>
  </div>
</template>


<script>
import { updateDish } from '@/api/dishes';
import { uploadImage } from '@/api/utils';
import { getIngredientsByDishId, addDishIngredient, deleteDishIngredient, getAllIngredients } from '@/api/ingredients';

export default {
  name: 'DishEditCard',
  props: {
    dish: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      form: {...this.dish, imageUrl: ''},
      selectedFile: null,
      ingredients: [], // Stores ingredients associated with the dish
      allIngredients: [], // Stores all available ingredients
      currentDishIngredients: [], // 存储当前菜品的原料列表
    };
  },
  mounted() {
    this.fetchIngredients();
    this.fetchAllIngredients();

    document.addEventListener('keydown', this.handleKeydown);

  },
  beforeDestroy() {
    document.removeEventListener('keydown', this.handleKeydown);
  },
  methods: {


    async handleCheckboxChange(ingredientId, event) {
      try {
        if (event.target.checked) {
          await addDishIngredient(this.dish.dish_id, ingredientId);
          // Add the ingredient to the ingredients array
        } else {
          await deleteDishIngredient(this.dish.dish_id, ingredientId);
          // Remove the ingredient from the ingredients array
        }
      } catch (error) {
        console.error('Error updating ingredient association:', error);
        // Optionally, revert the checkbox state here
      }
    },

    isIngredientSelected(ingredientId) {
      return this.currentDishIngredients.some(ingredient => ingredient.ingredient_id === ingredientId);
    },


    async fetchIngredients() {
      // console.log('111Fetching ingredients for dish:', this.dish); // 打印当前的 dish 对象

      if (this.dish && this.dish.dish_id) {
        try {
          // console.log('222Fetching ingredients for dish:', this.dish); // 打印当前的 dish 对象

          const response = await getIngredientsByDishId(this.dish.dish_id);
          if (response && response.data) {
            this.currentDishIngredients = response.data;
          } else {
            console.error('Invalid response structure:', response);
            this.currentDishIngredients = [];
          }
        } catch (error) {
          console.error('Error fetching ingredients:', error);
          this.currentDishIngredients = [];
        }
      }
    },

    async fetchAllIngredients() {
      try {
        const response = await getAllIngredients();
        this.allIngredients = response.data;
      } catch (error) {
        console.error('Error fetching all ingredients:', error);
        this.allIngredients = [];
      }
    },

    close() {
      this.$emit('close');
    },
    handleKeydown(e) {
      if (e.key === 'Escape') {
        this.close();
      }
    },
    handleBackgroundClick() {
      this.$emit('close');
    },
    handleFileUpload(event) {
      this.selectedFile = event.target.files[0];
      try {
        const formData = new FormData();
        formData.append('file', this.selectedFile);

        // 获取前端上传的文件名
        const fileName = this.selectedFile.name;

        // 执行上传操作
        uploadImage(formData);

        // 拼接路径前缀和图片名
        this.form.image_url = `/images/dishes/${fileName}`;

      } catch (error) {
        console.error(error);
      }
    },
    async submitDish() {
      const dishData = {
        name: this.form.name,
        description: this.form.description,
        image_url: this.form.image_url,
        is_on_shelf: this.form.is_on_shelf,
        is_deleted: `no`,
      };

      try {
        console.log('TESTT'+dishData.is_deleted)
        let response = await updateDish(this.dish.dish_id, dishData);

        // Check for success response
        if (response && response.data) {
          alert(response.data.message || '菜品更新成功');
        } else {
          alert('Dish update failed');
        }

        this.close();
        this.$emit('update-success');
      } catch (error) {
        // Handle errors
        if (error.response && error.response.data) {
          alert(error.response.data.message || '菜品更新失败');
        } else {
          alert('菜品更新失败');
        }
        console.error('Error during dish update', error);
      }
    },
  },
  //这个imageURL有用吗
  watch: {
    dish(newVal) {
      this.form = { ...newVal, imageUrl: '' };
      if (newVal.dish_id) {
        this.fetchIngredients();
        this.fetchAllIngredients(); // Ensure all ingredients are updated
      }
    }
  }
  // watch: {
  //   dish(newVal, oldVal) {
  //     if (newVal.dish_id !== oldVal.dish_id) {
  //       this.fetchIngredients();
  //     }
  //   }
  // },

};
</script>

<style scoped>
.modal {
  z-index: 1000;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(0, 0, 0, 0.6);
}

.modal-content {
  background: white;
  padding: 20px;
  border-radius: 10px;
  text-align: center;
  width: 90vw; /* 或具体的固定宽度 */
  max-width: 900px; /* 最大宽度 */
  height: 70vh; /* 设定一个固定高度或最大高度 */
  max-height: 95vh; /* 最大高度 */
  overflow-y: auto; /* 垂直方向上溢出时显示滚动条 */
  box-shadow: 0 4px 10px rgba(0,0,0,0.2);
}

.close-button {
  float: right;
  font-size: 1.5em;
  cursor: pointer;
}

.content-container {
  display: flex;
  justify-content: space-between;
  height: 100%;
}

.left-panel {
  background-color: #f9f9f9;
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 15px;
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
}

.left-panel input[type="text"]{
  display: block;
  width: 100%;
  padding: 10px;
  margin: 10px auto;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-sizing: border-box;
  font-size: 16px;
}

.left-panel select{
  display: block;
  width: 20%;
  padding: 10px;
  margin: 10px auto;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-sizing: border-box;
  font-size: 16px;
}

.left-panel textarea {
  display: block;
  width: 100%;
  height: 30vh;
  padding: 10px;
  margin: 10px auto;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-sizing: border-box;
  font-size: 16px;
}

.left-panel button {
  display: block;
  width: 100%;
  background-color: #93bdd8;
  color: white;
  padding: 14px 20px;
  margin: 10px auto;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 18px;
  font-weight: bold;
}

.left-panel button:hover {
  background-color: #A4D3F1;
}

.left-panel input[type="file"] {
  margin-top: 15px;
  font-size: 14px;
}

.right-panel {
  flex: 1;
  margin: 0 5px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 70vh; /* 添加一个固定高度 */
  overflow-y: auto; /* 只在此panel内部显示滚动条 */
}

.right-panel table {
  width: 100%;
  border-collapse: collapse;
}

.right-panel th, .right-panel td {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: left;
}

.right-panel th {
  background-color: #f4f4f4;
  font-weight: bold;
}

.right-panel tr:nth-child(even) {
  background-color: #f9f9f9;
}

.table-container {
  background-color: #f9f9f9;
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 15px;
  width: 100%; /* 确保宽度填充整个容器 */
  box-sizing: border-box; /* 防止边框和内边距影响宽度 */
  overflow-y: auto; /* 在需要时显示滚动条 */
  max-height: 70vh; /* 设置一个最大高度 */
}
</style>
